package noema.bam;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import noema.interceptor.LoggerInterceptor;

import org.jbpm.process.audit.NodeInstanceLog;
import org.jbpm.process.audit.ProcessInstanceLog;
import org.jbpm.process.audit.VariableInstanceLog;


@Interceptors({ LoggerInterceptor.class })
@Stateless
public class InstanceMonitoringImpl implements InstanceMonitoring {

	@PersistenceContext(unitName = "org.jbpm.persistence.jpa")
	private EntityManager em;

	@Override
	public List<Long> getIdsOfActiveProcess() {
		List<Long> processesId = new ArrayList<Long>();
		@SuppressWarnings("unchecked")
		List<ProcessInstanceLog> result = em.createQuery(
				"SELECT p FROM org.jbpm.process.audit.ProcessInstanceLog p "
						+ "WHERE p.end IS NULL").getResultList();
		for (ProcessInstanceLog p : result) {
			processesId.add(p.getProcessInstanceId());
		}
		return processesId;
	}

	@Override
	public NodeInstanceLog getActualNodeOfInstance(long instanceId) {
		Query q = em
				.createQuery("SELECT n FROM org.jbpm.process.audit.NodeInstanceLog n "
						+ "WHERE n.processInstanceId=:instanceId ORDER BY n.date DESC");
		q.setParameter("instanceId", instanceId);
		q.setMaxResults(1);
		try {
			return (NodeInstanceLog) q.getSingleResult();
		} catch (NoResultException e) {
			System.out.println("No log for instance with id=" + instanceId);
		}
		return null;
	}

	@Override
	public VariableInstanceLog getVariableOfInstance(long instanceId,
			String variableName) {
		Query q = em
				.createQuery("SELECT v FROM org.jbpm.process.audit.VariableInstanceLog v "
						+ "WHERE v.processInstanceId=:instanceId AND v.variableId=:variableId "
						+ "ORDER BY v.date DESC");
		q.setParameter("instanceId", instanceId);
		q.setParameter("variableId", variableName);
		q.setMaxResults(1);
		try {
			return (VariableInstanceLog) q.getSingleResult();
		} catch (NoResultException e) {
			System.out.println("No log for variable '" + variableName
					+ "' of instance with id=" + instanceId);
		}
		return null;
	}

}
